/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumNumbers = function (root) {
  let totalSum = 0;

  function dfs(node, currentSum) {
    if (node === null) {
      return;
    }

    // 计算当前路径的数字
    currentSum = currentSum * 10 + node.val;

    // 如果是叶子节点，将当前路径的数字加入总和
    if (node.left === null && node.right === null) {
      totalSum += currentSum;
      return;
    }

    // 递归遍历左子树和右子树
    dfs(node.left, currentSum);
    dfs(node.right, currentSum);
  }

  dfs(root, 0);
  return totalSum;
};